package org.infodavid.common.impl.services.validators;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.persistence.PersistenceException;

import org.infodavid.common.model.components.ILocation;
import org.infodavid.common.services.IApplicationContext;
import org.infodavid.common.services.exception.DuplicatedEntityException;
import org.infodavid.common.services.exceptions.ServiceException;

/**
 * The Class DefaultLocationValidator.
 */
public class DefaultLocationValidator extends AbstractValidator<ILocation> {

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.services.validators.IValidator#validate(org.infodavid.common.services.
	 * IApplicationContext, java.io.Serializable)
	 */
	public void validate(final IApplicationContext context, final ILocation value)
	    throws ServiceException {
		super.validate(context, value);
	}

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.services.validators.IValidator#validate(org.infodavid.common.services.
	 * IApplicationContext, java.util.Collection)
	 */
	public void validate(final IApplicationContext context, final Collection<ILocation> items)
	    throws ServiceException, PersistenceException {
		final Set<String> stringSet = new HashSet<String>();

		if (items == null || items.size() == 0) {}
		else {
			final Iterator<ILocation> ite = items.iterator();
			ILocation item;

			while (ite.hasNext()) {
				item = ite.next();

				if (item == null) {
					throw new IllegalArgumentException(ILocation.LOCATION);
				}
				else if (item.getName() == null) {
					validate(context, item);
				}
				else if (stringSet.contains(item.getName())) {
					throw new DuplicatedEntityException(ILocation.class, item.getName());
				}
				else {
					validate(context, item);
					stringSet.add(item.getName());
				}
			}
		}
	}
}
